/*  请求方法 */
import { deleteStore, getStore } from '@/utils/storage'
import { showToast } from '@/utils/message'
import { useAccountStore } from '@/store'
import type { IRequest, IUpload } from '@/types/utils/request'
import { HTTP_CODE, STORAGE_KEYS } from '@/common/constants'
import { REGEXP_FN } from '@/utils/regExp'
type ReloadOptionType =
  | {
      num: number
    }
  | undefined
  | null
const BASE_URL = import.meta.env.VITE_BASE_URL
console.log('BASE_URL', BASE_URL)
export const request = async (options: IRequest, reloadOption: ReloadOptionType = { num: 1 }) => {
  const storageToken = getStore(STORAGE_KEYS.TOKEN)
  // 判断是否需要token
  // if (!options.noToken && !storageToken) {
  //   const accountSotre = useAccountStore()
  //   storageToken = await accountSotre.loginAction()
  // }
  // 判断请求url是否为绝对路径
  if (!REGEXP_FN.link(options.url)) {
    options.url = BASE_URL + options.url
  }
  const header = options.header || {}
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      data: options.data || {},
      header: {
        Authorization: `Bearer ${storageToken || ''}`,
        ...header
      },
      success: async (res: any) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          if ([HTTP_CODE.TOKEN_INVALID, HTTP_CODE.TOKEN_EXPIRED].includes(res.data.code)) {
            deleteStore(STORAGE_KEYS.TOKEN)
            const accountSotre = useAccountStore()
            accountSotre.setToken('')
            accountSotre.setUserInfo({})
            // try {
            //   if (reloadOption && reloadOption.num) {
            //     if (reloadOption.num <= 0) {
            //       reject(res)
            //     }
            //     reloadOption.num--
            //     const response = await request(options, reloadOption)
            //     resolve(response)
            //   }
            //   resolve(res)
            // } catch (err) {
            // }
            showToast('登录失效,请重新登录')
            await accountSotre.checkNeedGetPhone()
            reject(res.data)
          }
          if ([HTTP_CODE.NOT_URL, HTTP_CODE.SERVER_ERROR].includes(res.data.code)) {
            showToast(res.data.msg || '请求失败,请重试')
            reject(res.data)
          }
          resolve(res.data.data)
        } else {
          showToast('发生错误,请联系管理员')
          reject(res)
        }
      },
      fail: (err: any) => {
        reject(err)
      }
    })
  })
}

export const upload = (options: IUpload) => {
  return new Promise((resolve, reject) => {
    const storageToken = getStore(STORAGE_KEYS.TOKEN)
    // 判断请求url是否为绝对路径
    if (!REGEXP_FN.link(options.url)) {
      options.url = BASE_URL + options.url
    }
    uni.uploadFile({
      url: options.url,
      name: options.name || 'file',
      filePath: options.filePath || '',
      ...options,
      header: {
        Authorization: `Bearer ${storageToken || ''}`
      },
      success: (res: any) => {
        console.log('[ upload ] >', res)
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(JSON.parse(res.data))
        } else {
          showToast(`上传失败：${res.data.msg || '未知错误'}`)
          reject(res.data)
        }
      },
      fail: (err: any) => {
        console.log('[ err ] >', err)
        reject(err)
      }
    })
  })
}
